package top.healthylife.basics.utils.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 根据ip获取用户的地址位置
 *
 * @author maoxiaomeng
 */
public class AddressUtils {

    private static final Logger logger = LoggerFactory.getLogger(AddressUtils.class);
    /**
     * 这里调用pconline的接口
     */
    private static final String URL = "https://ip.taobao.com/outGetIpInfo";

//    调用示例
//    public static void main(String[] args) {
//        String addresses = getAddress("183.230.165.74");
//        System.out.println("addresses = " + addresses);
//         addresses = 中国-重庆-移动
//    }
    public static String getAddress(String ip){
        String content = "ip="+ip;
        return getAddress(content,"UTF-8");
    }

    /**
     * @param content        请求的参数 格式为：name=xxx&pwd=xxx
     * @param encodingString 服务器端请求编码。如GBK,UTF-8等
     * @return String 请求结果
     */
    public static String getAddress(String content, String encodingString) {
        try {
            String returnStr = getResult(content, encodingString);
            String address = null;
            if (returnStr != null) {
                JSONObject jsonObject = JSONObject.parseObject(returnStr);
                int code = (int) jsonObject.get("code");
                if (code == 0) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if(data!=null){
                    address = data.getString("country") +"-"+ data.getString("city") +"-"+data.getString("isp");
                    }
                }
                return address;
            }
        } catch (Exception e) {
            logger.warn("数据结构异常,解析来自[淘宝ip地址库]的响应失败,本次ip未获取到对应地址信息");
            return null;
        }
        return null;
    }

    /**
     * 获取请求的结果
     *
     * @param content  请求的参数 格式为：name=xxx&pwd=xxx
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
     * @return 请求结果
     */
    private static String getResult(String content, String encoding) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(URL);
            // 新建连接实例
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间，单位毫秒
            connection.setConnectTimeout(2000);
            // 设置读取数据超时时间，单位毫秒
            connection.setReadTimeout(33000);
            // 是否打开输出流 true|false
            connection.setDoOutput(true);
            // 是否打开输入流true|false
            connection.setDoInput(true);
            // 提交方法POST|GET
            connection.setRequestMethod("POST");
            // 是否缓存true|false
            connection.setUseCaches(false);
            // 打开连接端口
            connection.connect();
            // 打开输出流往对端服务器写数据
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(content);
            // 刷新
            out.flush();
            // 关闭输出流
            out.close();
            // 往对端写完数据对端服务器返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
            // ,以BufferedReader流来读取
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
            return builder.toString();
        } catch (IOException e) {
            logger.error("调用淘宝通过ip获取地理位置服务发生异常", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }


    /**
     * unicode 转换成 中文
     *
     * @param theString 字符串
     * @return String
     */
    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuilder builder = new StringBuilder(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException("Malformed   encoding.");
                        }
                    }
                    builder.append((char) value);
                } else {
                    if (aChar == 't') {
                        aChar = '\t';
                    } else if (aChar == 'r') {
                        aChar = '\r';
                    } else if (aChar == 'n') {
                        aChar = '\n';
                    } else if (aChar == 'f') {
                        aChar = '\f';
                    }
                    builder.append(aChar);
                }
            } else {
                builder.append(aChar);
            }
        }
        return builder.toString();
    }
}